package com.service.single.service.impl;

import cn.hutool.core.io.file.FileReader;
import com.service.single.entity.FileInfo;
import com.service.single.service.ElasticsearchService;
import com.service.single.service.FileParseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.util.List;

/**
 * @Author: 一休
 * @DateTime: 2022/11/2 15:57
 */
@Slf4j
@Service
public class DocxParseServiceImpl implements FileParseService {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Override
    public void fileParse(FileInfo fileInfo) {
        Integer fileType = fileInfo.getFileType();
        String filePath = fileInfo.getFilePath();
        if (fileType != 2) {
            return;
        }
        FileReader fileReader = new FileReader(filePath);
        BufferedInputStream inputStream = fileReader.getInputStream();
        try {
            XWPFDocument document = new XWPFDocument(inputStream);
            // 读取段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            StringBuilder builder = new StringBuilder();
            for (XWPFParagraph paragraph : paragraphs) {
                String text = paragraph.getParagraphText();
                builder.append(text);
            }
            elasticsearchService.insertFileContent(fileInfo, builder);
        } catch (Exception e) {
            log.error("docx文件解析异常 {}", e.getMessage());
        }

    }
}
